import 'dart:io';

import 'package:flutter/services.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:url_launcher/url_launcher.dart';

class Bridge {
  static Future<String> getIp() async {
    try {
      if (Platform.isWindows) {
        return await _getIPForWindows();
      } else if (Platform.isAndroid) {
        return await _getIpForAndroid();
      }
    } on PlatformException {
      return "";
    }
  }

  static Future<String> _getIPForWindows() async {
    var interfaces = await NetworkInterface.list(
        includeLoopback: false, type: InternetAddressType.any);

    String _address = "";

     interfaces.forEach((interface) {
      interface.addresses.forEach((address) {
        if (address.address.startsWith("17")) {
          print(address.address);
          _address= address.address;
        }
      });
    });

    return _address;
  }

  static Future<String> getUserInfo() async {
    try {
      var prefs = await SharedPreferences.getInstance();
      return prefs.getString('UserInfo');
    } on PlatformException {
      return "";
    }
  }

  static Future<void> saveUserInfo(String userInfo) async {
    try {
      var prefs = await SharedPreferences.getInstance();
      prefs.setString('UserInfo', userInfo);
    } on PlatformException {}
  }

  static void openUrl(String url) {
    try {
      launch(url);
    } on PlatformException {}
  }

  static Future<String> _getIpForAndroid() async {
    var _platform = const MethodChannel('cn.kaicity/flutter');
    return await _platform.invokeMethod('getIp');
  }
}
